//
//  ZPAddBlacklistView.m
//  HCNewGoldFinger
//
//  Created by 刘琛 on 2018/2/1.
//  Copyright © 2018年 zjhcsoftios. All rights reserved.
//

#import "ZPAddBlacklistView.h"
#import "ZPBlackManageModel.h"
#import "DatePickerView.h"
#import "LeadPickerView.h"
#import "NSBundle+AssociatedBundle.h"
#import "iSeeNetworkRequest.h"
#import "NetworkAddress.h"
#import "SVProgressHUD.h"

@interface ZPAddBlacklistView ()<LDSTPickerViewDelegate,UITextFieldDelegate>

@property (nonatomic, strong) NSMutableArray *approverList;

@property (nonatomic, assign) BOOL isApprover;

@property (nonatomic, strong ) NSString *phoneNum;

@property (weak, nonatomic) IBOutlet UITextField *remarksField;
@property (weak, nonatomic) IBOutlet UILabel *startLabel;
@property (weak, nonatomic) IBOutlet UILabel *endLabel;

@property (weak, nonatomic) IBOutlet UIView *blackView;



@property (weak, nonatomic) IBOutlet UILabel *approverLabel;
@property (nonatomic, strong) LeadPickerView *approverPicker;
@property (nonatomic, strong) ZPBlackManageModel *selectedApprover;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *approveViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *blackViewHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *centerLineHeight;

@end

@implementation ZPAddBlacklistView

#pragma mark 初始化
- (void)awakeFromNib {
    [super awakeFromNib];
    
    _approverList = [NSMutableArray array];
    
    [self getApproverList];
    
    _remarksField.delegate = self;
    
    for (int i = 0; i < 4; i++) {
        UIView *backView = [self viewWithTag:100 + i];
        backView.layer.borderWidth = 1;
        backView.layer.borderColor = [UIColor colorWithRed:219/255.0 green:221/255.0 blue:225/255.0 alpha:1].CGColor;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backViewAction:)];
        [backView addGestureRecognizer:tap];
    }
//    UITapGestureRecognizer *dismissTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismiss)];
//    [self addGestureRecognizer:dismissTap];
}


- (void)setPhoneNum:(NSString *)phoneNum {
    _phoneNum = phoneNum;
}


#pragma mark 网络请求
// 获取列表
- (void)getApproverList {
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPApproverList) params:[NSDictionary dictionary] success:^(id object) {
        self.isApprover = [object[@"body"][@"blackListRole"] boolValue];
        if (!self.isApprover) {
            [self.approverList addObjectsFromArray:[ZPBlackManageModel mj_objectArrayWithKeyValuesArray:object[@"body"][@"blackManageList"]]];
            self.approverPicker = [[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"] loadNibNamed:@"LeadPickerView" owner:self options:nil].lastObject;
            self.approverPicker.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            self.approverPicker.delegate = self;
            [self showApproverBackView];
        }
    } failure:^(NSError *error) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [dic objectForKey:@"msg"];
        [SVProgressHUD showErrorWithStatus:msg];
    }];
    
}
// 加入黑名单
- (void)addBlackList {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:_phoneNum forKey:@"phoneNumber"];
    [params setObject:self.remarksField.text forKey:@"msgContent"];
    [params setObject:[_startLabel.text stringByReplacingOccurrencesOfString:@"-" withString:@""] forKey:@"effectTime"];
    [params setObject:[_endLabel.text stringByReplacingOccurrencesOfString:@"-" withString:@""] forKey:@"failureTime"];
    if (!_isApprover) {
        [params setObject:_selectedApprover.USERID forKey:@"approvalUserId"];
        [params setObject:_selectedApprover.USERNAME forKey:@"approvalUserName"];
    }
    
    [iSeeNetworkRequest getWithHeaderUrl:kFormat(@"%@%@",NMarketMainUrl,ZPheimingdan) params:params success:^(id object) {
        
        [SVProgressHUD showSuccessWithStatus:@"黑名单申请提交成功"];
    } failure:^(NSError *error) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [dic objectForKey:@"msg"];
        [SVProgressHUD showErrorWithStatus:msg];
    }];

}

#pragma mark 代理
- (void)pickerView:(LeadPickerView *)leadPickerView AndSelected:(NSString *)areaId AndTitle:(NSString *)title AndType:(NSInteger)type {
    
    if (type == 1) {
        for (ZPBlackManageModel *model in _approverList) {
            if ([model.USERNAME isEqualToString:title]) {
                _selectedApprover = model;
                _approverLabel.text = _selectedApprover.USERNAME;
                return;
            }
        }
    }
    
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self endEditing:YES];
    return YES;
}


#pragma mark 点击事件

- (IBAction)cannelButtonAction:(id)sender {
    [self dismiss];
}


- (IBAction)tureButtonAction:(id)sender {
    
    if (_isApprover) {
        
    }
    if (_remarksField.text.length > 0 && _endLabel.text.length > 0 && _startLabel.text.length > 0) {
        if (_isApprover || (!_isApprover && _selectedApprover)) {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            //设置格式：zzz表示时区
            [dateFormatter setDateFormat:@"yyyy-MM-dd"];
            NSDate *startDate = [dateFormatter dateFromString:_startLabel.text];
            NSDate *endDate = [dateFormatter dateFromString:_endLabel.text];
            
            if ([[startDate earlierDate:endDate] isEqualToDate:startDate]) {
                
                [self addBlackList];
            }else {
                [SVProgressHUD showErrorWithStatus:@"失效时间小于生效时间"];
            }
        }else {
            [SVProgressHUD showErrorWithStatus:@"请选择审核人"];
        }
    }else {
        if (_remarksField.text.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请输入添加黑名单原因"];
        }else if (_startLabel.text.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请选择生效时间"];
        }else if (_endLabel.text.length == 0) {
            [SVProgressHUD showErrorWithStatus:@"请选择失效时间"];
        }
    }
}


- (void)backViewAction:(UITapGestureRecognizer *) tap {
    switch (tap.view.tag - 100) {
        case 0:
            [self startTimeButtonAction];
            [self endEditing:YES];
            break;
        case 1:
            [self endTimeButtonAction];
            [self endEditing:YES];
            break;
        case 2:
            [self.remarksField becomeFirstResponder];
            break;
        case 3:
            [self approverButtonAction];
            [self endEditing:YES];
            break;
        default:
            break;
    }
}



- (void)startTimeButtonAction {
    
    [DatePickerView showDatePickerInView:self.window success:^(NSDate *date) {
        
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *startTime = [dateFormatter stringFromDate:date];
        
        if (![self.endLabel.text isEqualToString:@"请选择失效时间"]) {
            NSDate *endDate = [dateFormatter dateFromString:self.endLabel.text];
            if ([[endDate laterDate:date] isEqualToDate:endDate] && ![self.endLabel.text isEqualToString:startTime]) {
                self.startLabel.text = startTime;
            }else {
                [SVProgressHUD showErrorWithStatus:@"生效时间设置错误"];
            }
        }else {
            self.startLabel.text = startTime;
        }
        
    } failure:^{
        
    }];
}

- (void)endTimeButtonAction {
    [DatePickerView showDatePickerInView:self.window success:^(NSDate *date) {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *endTime = [dateFormatter stringFromDate:date];
        

        if (![self.startLabel.text isEqualToString:@"请选择生效时间"]) {
            NSDate *startDate = [dateFormatter dateFromString:self.startLabel.text];
            if ([[date laterDate:startDate] isEqualToDate:date] && ![self.startLabel.text isEqualToString:endTime]) {
                self.endLabel.text = endTime;
            }else {
                [SVProgressHUD showErrorWithStatus:@"失效时间设置错误"];
            }
        }else {
            self.endLabel.text = endTime;
        }
        
    } failure:^{
        
    }];
}

- (void)approverButtonAction {

    if (_approverList.count > 0) {
        
        NSMutableArray *nameArray = [NSMutableArray array];
        for (ZPBlackManageModel *approver in _approverList) {
            [nameArray addObject:approver.USERNAME];
        }
        _approverPicker.timeArray = nameArray;
        [self.window addSubview:_approverPicker];
    }
}

#pragma mark 页面显示及消失
+ (void)showBlacklistViewPhoneNum:(NSString *) phoneNum {
    
    ZPAddBlacklistView *blacklist = [[NSBundle bundleWithBundleName:@"NewMarketLib" podName:@"NewMarketLib"] loadNibNamed:@"ZPAddBlacklistView" owner:self options:nil].lastObject;
    blacklist.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    blacklist.phoneNum = phoneNum;
    [blacklist.window addSubview:blacklist];
    [blacklist show];
    
}

- (void)hiddenApproverBackView {
    _approveViewHeight.constant = 0;
    _blackViewHeight.constant = 330 - 55;
    _centerLineHeight.constant = 223 - 55;
    UIView *view = [self viewWithTag:200];
    [UIView animateWithDuration:.25 animations:^{
        view.hidden = YES;
        [self layoutIfNeeded];
    }];
}

- (void)showApproverBackView {
    _approveViewHeight.constant = 55;
    _blackViewHeight.constant = 330 ;
    _centerLineHeight.constant = 223;
    UIView *view = [self viewWithTag:200];
    [UIView animateWithDuration:.25 animations:^{
        view.hidden = NO;
        [self layoutIfNeeded];
    }];
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self endEditing:YES];
}

- (void)show {
    [UIView animateWithDuration:.25 animations:^{
        self.blackView.alpha = 1;
    }];
}

- (void)dismiss {
    [UIView animateWithDuration:.25 animations:^{
        self.blackView.alpha = 0;
    } completion:^(BOOL finished) {
        [self endEditing:YES];
        [self removeFromSuperview];
    }];
}

@end
